package polygon.cli.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author MikeMirzayanov (mirzayanovmr@gmail.com)
 */
public class InvocationUtil {
    public static boolean run(File dir, String... commandLine) throws IOException, InterruptedException {
        Process process = new ProcessBuilder().directory(dir).command(commandLine).start();

        final InputStream inputStream = process.getInputStream();
        new Thread(new Runnable() {
            public void run() {
                try {
                    byte[] bytes = new byte[1023];
                    while (true) {
                        int count = inputStream.read(bytes);
                        if (count < 0) {
                            break;
                        } else {
                            System.out.write(bytes, 0, count);
                        }
                    }
                } catch (IOException e) {
                    // No operations.
                }
            }
        }).start();

        process.waitFor();

        return process.exitValue() == 0;
    }
}
